/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-11-20 20:58:30
 ******************************************************************************/
package cn.com.xy.sms.util;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.PhoneSmsParseManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.DuoquUtils;
import cn.com.xy.sms.sdk.util.KeyManager;
import cn.com.xy.sms.sdk.util.PopupUtil;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;

public class ParseSmsToBubbleUtil {
    // Cache type of the return data 1:Returns the SDK cache id
    public static final byte RETURN_CACHE_SDK_MSG_ID = 1;
    // Cache type of the return data 2: Returns the recognition results, Save it
    // by the developer or identification results.
    public static final byte RETURN_CACHE_SDK_MSG_VALUE = 2;

    /***
     * history receivesms parse beforeHand
     * 
     * @param maxLimit
     *            each time parse max count
     * @param type
     *            1:simple 2:rich 3:simple and rich together
     */
    public static void beforeHandParseReceiveSms(final int maxLimit, final int type) {
        beforeHandParseReceiveSms(null, maxLimit, type, false);
    }

    /***
     * history receivesms parse beforeHand
     * 
     * @param maxLimit
     *            each time parse max count
     * @param type
     *            1:simple 2:rich 3:simple and rich together
     */
    public static void beforeHandParseReceiveSms(final String phoneNum, final int maxLimit, final int type, boolean resultAddMemory) {
        final boolean allTable = StringUtils.isNull(phoneNum) ? true : false;
        BeforeParseUtil.executeBeforeParse(allTable, phoneNum, maxLimit, type, resultAddMemory);
    }

    /**
     * @param msgId
     * @param phoneNum
     * @param smsContent
     * @param centerNum
     * @param smsReceiveTime
     * @param dataType
     *            1:simple bubble 2:rich bubble 3:simple and rich bubble
     *            4:notify simple and rich bubble
     */
    public static Map<String, Object> parseSmsToBubbleResultMap(final String msgId, final String phoneNum, final String smsContent, final String centerNum, final long smsReceiveTime, final int dataType, final boolean allTable, final boolean resultAddMemory, Map<String, String> extend) {
        try {
            /* SDK-402 huangzhiqiang 20160420 start */
            extend = ParseManager.putValueToMap(extend, "msgId", msgId);
            if (extend!=null) {
                /* SDK-603 zhaojiangwei 20160831 start */
                String time = null;
                /* SDK-657 zhaojiangwei 20161101 start */
                if (extend.containsKey("msgTime")) {
                	time = extend.get("msgTime");
    			}
                /* SDK-657 zhaojiangwei 20161101 end */
                if (StringUtils.isNull(time)) {
                    extend.put("msgTime", String.valueOf(smsReceiveTime));
                }
                /* SDK-603 zhaojiangwei 20160831 end */
                /* SDK-402 huangzhiqiang 20160420 end */
                /* SDK-383 xusongzhou 20160412 start */
                if(DuoquUtils.getSdkDoAction().needRecognisedValue() ) {
                    extend.put("parse_recognise_value", "true");
                }
                /* SDK-383 xusongzhou 20160412 end */
			}
            final Map<String, Object> resultMap = ParseManager.parseMsg(Constant.getContext(), phoneNum, centerNum, smsContent, smsReceiveTime, extend);
            LogManager.d("kk", "ParseManager resultMap ="+resultMap);
            if(resultMap != null)
                DuoquUtils.getSdkDoAction().updateSmsSceneId(msgId,(String)resultMap.get("title_num"));
            if (ParseBubbleManager.getParseStatu(resultMap) == -1) {
                return null;
            }
            if (dataType == 4) {
                Map<String, Object> res = null;
                if (resultMap == null) {
                    return null;
                }
                res = new HashMap<String, Object>();
                res.putAll(resultMap); // 通知栏数据同步方式响应
                backGroundParseSmsBubble(msgId, phoneNum, smsContent, centerNum, smsReceiveTime, allTable, resultAddMemory, resultMap,extend);
                return res;
            } else {
                return parseSmsToBubbleResult1(msgId, phoneNum, smsContent, centerNum, smsReceiveTime, dataType, allTable, resultAddMemory, resultMap,extend);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "parseSmsToBubbleResultMap: ", e);

        }
        return null;
    }

    protected static void backGroundParseSmsBubble(final String msgId, final String phoneNum, final String smsContent, final String centerNum, final long smsReceiveTime, final boolean allTable, final boolean resultAddMemory, final Map<String, Object> resultMap,final Map<String, String> extend) {
        Thread thread = new Thread() {
            @Override
            public void run() {
            	try {
					this.setName("xiaoyuan-parseSmsToBubble");
                parseSmsToBubbleResult1(msgId, phoneNum, smsContent, centerNum, smsReceiveTime, 3, allTable, resultAddMemory, resultMap,extend);
				} catch (Throwable e) {
					LogManager.e(Constant.TAG, e.getMessage(), e);
				}
            };
        };
        thread.start();
    }

    protected static void backGroundHandleMapByType(final Map<String, String> params, final Map<String, Object> resultMap) {
        if (params == null) {
            return;
        }
        final String handleType = params.get("handle_type");
        if (StringUtils.isNull(handleType)) {
            return;
        }
        Thread thread = new Thread() {
            @Override
            public void run() {
            	try {
					 this.setName("xiaoyuan-parseSmsToBubble1");
                try {
                    int type = Integer.valueOf(handleType);
                    Map<String, Object> res = DexUtil.handerValueMapByType(type, resultMap);
                    if (res != null) {
                        DuoquUtils.getSdkDoAction().parseMsgCallBack(type, res);
                    }
                } catch (Throwable e) {
//                    e.printStackTrace();
                    LogManager.e(Constant.TAG, "backGroundHandleMapByType: ", e);

                }
            
				} catch (Throwable e) {
					LogManager.e(Constant.TAG, e.getMessage(), e);
				}
               };
        };
        thread.start();
    }

    /**
     * @param msgId
     * @param phoneNum
     * @param smsContent
     * @param centerNum
     * @param smsReceiveTime
     * @param dataType
     *            1:simple bubble 2:rich bubble 3:simple and rich bubble
     *            4:notify simple and rich bubble
     */
    public static Map<String, Object> parseSmsToBubbleResult(final String msgId, final String phoneNum, final String smsContent, final String centerNum, final long smsReceiveTime, final int dataType, final boolean allTable, final boolean resultAddMemory, final HashMap<String, Object> extend) {
        return parseSmsToBubbleResultMap(msgId, phoneNum, smsContent, centerNum, smsReceiveTime, dataType, allTable, resultAddMemory, XyUtil.changeObjMapToStrMap(extend));
    }

    /**
     * @param msgId
     * @param phoneNum
     * @param smsContent
     * @param centerNum
     * @param smsReceiveTime
     * @param dataType
     *            1:simple bubble 2:rich bubble 3:simple and rich bubble
     */
    private static Map<String, Object> parseSmsToBubbleResult1(String msgId, String phoneNum, String smsContent, String centerNum, long smsReceiveTime, int dataType, boolean allTable, boolean resultAddMemory, final Map<String, Object> resultMap,Map<String, String> extend) {
        Map<String, Object> result = null;
        try {
            // parse msg pick core key data
            if (resultMap != null) {
                switch (dataType) {
                case 1:
                    // save simple data
                    result = saveSimpleBubbleResult(msgId, phoneNum, smsContent, centerNum, smsReceiveTime, resultMap, resultAddMemory,extend);
                    break;
                case 2:
                    // save rich data
                    result = saveRichBubbleResult(msgId, phoneNum, smsContent, centerNum, smsReceiveTime, resultMap, resultAddMemory);
                    break;
                case 3:
                    // save simple data
                    result = saveSimpleBubbleResult(msgId, phoneNum, smsContent, centerNum, smsReceiveTime, resultMap, resultAddMemory,extend);
                    // save rich data
                    Map<String, Object> resultTemp = saveRichBubbleResult(msgId, phoneNum, smsContent, centerNum, smsReceiveTime, resultMap, resultAddMemory);
                    if (result == null) {
                        result = resultTemp;
                    } else {

                        if (result != null && resultTemp != null && !resultTemp.isEmpty()) {
                            result.putAll(resultTemp);
                        }
                    }
                    break;
                }
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "parseSmsToBubbleResult1: ", e);

        }
        String bubbleViewStr = null;
        if (result != null) {
            bubbleViewStr = (String) result.get("View_fdes");
        }
        if (allTable) {
            smsReceiveTime = 0;
        }
        PhoneSmsParseManager.addInsertQueue(phoneNum, smsReceiveTime, bubbleViewStr, null, null);
        return result;
    }

    /**
     * save simple bubble data
     * 
     * @param msgId
     * @param phoneNum
     * @param smsContent
     * @param centerNum
     * @param smsReceiveTime
     * @param resultMap
     * @return
     */
    static Map<String, Object> saveSimpleBubbleResult(String msgId, String phoneNum, String smsContent, String centerNum, long smsReceiveTime, Map<String, Object> resultMap, boolean resultAddMemory,Map<String, String> extend) {
        Map<String, Object> result = null;
        try {
            result = PopupUtil.parseMsgToSimpleBubbleResult(Constant.getContext(), msgId, phoneNum, centerNum, smsContent, smsReceiveTime, RETURN_CACHE_SDK_MSG_ID, resultMap, resultAddMemory,extend);
        } catch (Throwable e) {
            // TODO Auto-generated catch block
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "saveSimpleBubbleResult: ", e);

        }
        return result;
    }

    /**
     * save rich bubble data
     * 
     * @param msgId
     * @param phoneNum
     * @param smsContent
     * @param centerNum
     * @param smsReceiveTime
     * @param resultMap
     * @return
     */
    static Map<String, Object> saveRichBubbleResult(String msgId, String phoneNum, String smsContent, String centerNum, long smsReceiveTime, Map<String, Object> resultMap, boolean resultAddToMemory) {
        // 封装解析结果供汽泡视图显示使用
        Map<String, Object> cardResult = null;
        try {
            cardResult = PopupUtil.parseMsgToBubbleCardResult(Constant.getContext(), msgId, phoneNum, centerNum, smsContent, smsReceiveTime, RETURN_CACHE_SDK_MSG_ID, resultMap, resultAddToMemory);
            if(cardResult!=null){
                JSONObject bubbleObj = (JSONObject)cardResult.get("BUBBLE_JSON_RESULT");
                statisticRichBubbleDataReady(bubbleObj);
            }
            // LogManager.d("ParseSmsToBubbleUtil",
            // "cardResult: "+cardResult+"   smsContent="+smsContent+" phoneNum="+phoneNum);
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "saveRichBubbleResult: ", e);

        }
        return cardResult;
    }
    
    /*SMARTISAN-416 zhaojiangwei 20170217 start */
    private static void statisticRichBubbleDataReady(JSONObject bubbleObj){
        if (bubbleObj!=null) {
            if ("XRyvMvZwSMARTISAN".equals(KeyManager.channel)) {
                String titleNum = bubbleObj.optString("title_num");
                String newAdaction = bubbleObj.optString("NEW_ADACTION");

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("parse_title_num", titleNum);
                map.put("parse_new_adaction", newAdaction);
                DuoquUtils.getSdkDoAction().logInfo("firstParse", "", map);
            }
        }
    }
    /*SMARTISAN-416 zhaojiangwei 20170217 end */
}
